package com.classic.mafiacards;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class ManagerActivity extends ListActivity {

    Handler myHandler = new Handler();
    Vibrator vibrator;
    ListView lv;
    Button timer;

    PlayerAdapter adapter;

    int i;

    class PlayerAdapter extends ArrayAdapter<Player> {
        private ArrayList<Player> items;
        private PlayerViewHolder playerHolder;

        private class PlayerViewHolder {
            TextView title;
            TextView status;
            TextView role;
            CheckBox voted;
        }

        public PlayerAdapter(Context context, int tvResId, ArrayList<Player> items) {
            super(context, tvResId, items);
            this.items = items;
        }

        public boolean isEnabled(int position) {
            return items.get(position).in_game;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            View v = convertView;
            LayoutInflater vi = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.list_item_layout, null);
            playerHolder = new PlayerViewHolder();

            if (v != null) {
                playerHolder.title = (TextView) v.findViewById(R.id.title);
                playerHolder.status = (TextView) v.findViewById(R.id.status);
                playerHolder.role = (TextView) v.findViewById(R.id.role);
                playerHolder.voted = (CheckBox) v.findViewById(R.id.checkVote);
            }

            playerHolder.voted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    items.get(position).voted = isChecked;
                    adapter.notifyDataSetChanged();
                }
            });

            playerHolder.title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    createEditNameDialog(position).show();
                }
            });

            Player p = items.get(position);

            playerHolder.title.setText(p.name);
            playerHolder.status.setText(String.format(getString(R.string.manager_player_status),
                    String.valueOf(p.fouls), p.voted ? getString(R.string.yes)
                    : getString(R.string.no))
            );
            playerHolder.role.setText(getResources().getStringArray(R.array.roles)[p.role]);
            playerHolder.role.setVisibility(View.INVISIBLE);
            playerHolder.voted.setChecked(p.voted);

            if(!isEnabled(position)) {
                v.setClickable(true);
                playerHolder.voted.setEnabled(false);
                playerHolder.role.setVisibility(View.VISIBLE);
                playerHolder.role.setText(getString(R.string.list_role_left_us));
                playerHolder.title.setTextColor(getResources().
                        getColor(android.R.color.secondary_text_dark));
            }
            return v;
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manager);
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        adapter = new PlayerAdapter(this,
                R.layout.list_item_layout, CardsActivity.players);
        setListAdapter(adapter);

        lv = (ListView) findViewById(android.R.id.list);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                createFoulsDialog(position).show();
            }
        });

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.getItem(position).in_game = false;
                adapter.notifyDataSetChanged();
                return false;
            }
        });

        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState == SCROLL_STATE_IDLE) {
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        timer = (Button) findViewById(R.id.timerBtn);
        timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TimerValues.press_times % 2 == 0) {
                    TimerValues.startTime = SystemClock.uptimeMillis();
                    myHandler.postDelayed(updateTimerMethod, 0);
                } else {
                    TimerValues.timeSwap += TimerValues.timeInMillies;
                    myHandler.removeCallbacks(updateTimerMethod);
                }
                TimerValues.press_times++;
                i++;
                Handler handler = new Handler();
                Runnable r = new Runnable() {
                    public void run() {
                        i = 0;
                    }
                };
                if (i == 1) {
                    handler.postDelayed(r, 250);
                } else if (i == 2) {
                    i = 0;
                    TimerValues.press_times = 0;
                    TimerValues.timeSwap = 0;
                    TimerValues.finalTime = 0;
                    myHandler.removeCallbacks(updateTimerMethod);
                    timer.setText("00:00");
                }
            }
        });
    }

    private Runnable updateTimerMethod = new Runnable() {
        @Override
        public void run() {
            TimerValues.timeInMillies = SystemClock.uptimeMillis() - TimerValues.startTime;
            TimerValues.finalTime = TimerValues.timeSwap + TimerValues.timeInMillies;
            int seconds = (int) (TimerValues.finalTime / 1000) % 60;
            int milliseconds = (int) (TimerValues.finalTime % 1000);
            timer.setText(String.format("%02d", seconds) + ":"
                    + String.format("%02d", milliseconds / 10));
            myHandler.postDelayed(this, 0);
            if(TimerValues.finalTime / 100 == 599) {
                TimerValues.press_times++;
                TimerValues.timeSwap = 0;
                TimerValues.finalTime = 0;
                timer.setText("00:00");
                myHandler.removeCallbacks(updateTimerMethod);
                vibrator.vibrate(300);
            }
        }

    };

    private Dialog createEditNameDialog(final int position) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.alert_dialog_edit_name_title));
        String value;

        final EditText input = new EditText(this);
        input.setSingleLine(true);
        input.setSelectAllOnFocus(true);
        value = adapter.getItem(position).name.
                substring(0, adapter.getItem(position).name.indexOf(" "));
        input.setText(value);
        builder.setView(input);

        builder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                if (input.getText().length() != 0) {
                    String value = input.getText().toString();
                    value = Character.toUpperCase(value.charAt(0)) + value.substring(1);
                    adapter.getItem(position).name = value + " №" + String.valueOf(position + 1);
                    adapter.notifyDataSetChanged();
                }
            }
        });

        return builder.create();
    }

    private Dialog createFoulsDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
                .setTitle(getString(R.string.alert_dialog_fols_title))

                .setNeutralButton(getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {

                            }
                        })

                .setSingleChoiceItems(new String[]{"0", "1", "2", "3"}, adapter.getItem(position).fouls,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int item) {
                                adapter.getItem(position).fouls = item;
                                adapter.notifyDataSetChanged();
                                dialog.cancel();
                            }
                        });

        return builder.create();
    }

    private Dialog createGameInfoDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final TextView textView = new TextView(this);
        String text = "";

        for (Player player : adapter.items) {
            text += String.format("  %s - %s\n",
                    getResources().getStringArray(R.array.roles)[player.role],
                    player.name);
        }
        text = text.substring(0, text.length() - 1);

        builder.setTitle(getString(R.string.alert_dialog_game_info));
        textView.setText(text);
        builder.setView(textView);

        builder.setNeutralButton(getString(android.R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int id) {
                        dialog.cancel();
                    }
                });

        return builder.create();
    }

    public void onPause() {
        super.onPause();
        if (TimerValues.press_times % 2 == 1) {
            TimerValues.timeSwap += TimerValues.timeInMillies;
        }
        myHandler.removeCallbacks(updateTimerMethod);
    }

    public void onBackPressed() {
        startActivity(new Intent(this, TimerActivity.class).
                setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
    }

    public void onResume(){
        super.onResume();
        if(TimerValues.press_times % 2 == 1) {
            TimerValues.press_times++;
            timer.performClick();
        } else { 
            timer.setText(String.format("%02d", TimerValues.finalTime / 1000) + ":"
                + String.format("%02d", (TimerValues.finalTime % 1000) / 10));
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_new_day, menu);
        getMenuInflater().inflate(R.menu.menu_show_roles, menu);
        getMenuInflater().inflate(R.menu.menu_show_timer, menu);
        getMenuInflater().inflate(R.menu.menu_shuffle_cards, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_show_timer:
                this.onBackPressed();
                return true;
            case R.id.action_new_day:
                for (Player player : adapter.items) {
                    if (player.in_game)
                        player.voted = false;
                }
                adapter.notifyDataSetChanged();
                return true;
            case R.id.action_show_roles:
                createGameInfoDialog().show();
                return true;
            case R.id.action_shuffle_cards:
                new AlertDialog.Builder(this)

                        .setTitle(getString(R.string.alert_close_game_title))

                        .setMessage(getString(R.string.alert_dilaog_close_message))

                        .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int arg1) {
                                startActivity(new Intent(ManagerActivity.this, MainActivity.class).
                                        setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        })

                        .setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })

                        .show();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
